package com.example.maggie.meizinote.mvp.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;

import com.example.maggie.meizinote.app.MApp;
import com.iflytek.cloud.SpeechUtility;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.example.maggie.meizinote.di.component.DaggerNoteTTSComponent;
import com.example.maggie.meizinote.di.module.NoteTTSModule;
import com.example.maggie.meizinote.mvp.contract.NoteTTSContract;
import com.example.maggie.meizinote.mvp.presenter.NoteTTSPresenter;
import com.example.maggie.meizinote.R;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class NoteTTSActivity extends BaseActivity<NoteTTSPresenter> implements NoteTTSContract.View {
    @BindView(R.id.webview)
    WebView webview;
    private String content;
    @BindView(R.id.play)
    CheckBox play;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.layout)
    LinearLayout layout;

    @OnClick({R.id.play, R.id.toolbar_right_text})
    void onClick(View v) {
        switch (v.getId()) {
//            case R.id.play:
//                mPresenter.play(content, ((RadioButton) v).isClickable());
//                break;
            case R.id.toolbar_right_text:
                mPresenter.selectPersent();
                break;
        }
    }

    @Override
    public void setupActivityComponent(AppComponent appComponent) {
        DaggerNoteTTSComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .noteTTSModule(new NoteTTSModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(Bundle savedInstanceState) {
        return R.layout.activity_note_tts; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        setTitle("预览");
        content = getIntent().getStringExtra("content");
        mPresenter.initTTS(this);
        initWebView();
        play.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mPresenter.play(content, isChecked);
            }
        });
        webview.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
        dayOrNight();
    }

    public void dayOrNight() {
        if (MApp.isNight) {
            layout.setBackgroundColor(getResources().getColor(R.color.night_bg_color));
            toolbar.setBackgroundColor(getResources().getColor(R.color.night_toolbar_color));

            webview.setBackgroundColor(getResources().getColor(R.color.night_bg_color)); // 设置背景色
            webview.getBackground().setAlpha(0); // 设置填充透明度 范围：0-255
        } else {
            layout.setBackgroundColor(getResources().getColor(R.color.day_bg_color));
            toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
            webview.getBackground().setAlpha(255); // 设置填充透明度 范围：0-255
        }
        setColor();
    }

    public void setColor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            if (MApp.isNight)
                window.setStatusBarColor(getResources().getColor(R.color.night_toolbar_color));
            else
                window.setStatusBarColor(getResources().getColor(R.color.colorPrimary));
        }
    }


    private void initWebView() {
        webview.getSettings().setDefaultTextEncodingName("UTF-8");
        webview.setHorizontalScrollBarEnabled(false);// 设置滑动条水平不显示
        webview.setVerticalScrollBarEnabled(false); // 设置滑动条垂直不显示
        webview.getSettings().setJavaScriptEnabled(true);// 支持javascript
        webview.getSettings().setSupportZoom(true);// 设置可以支持缩放
        webview.getSettings().setBuiltInZoomControls(true);// 设置出现缩放工具
        webview.getSettings().setUseWideViewPort(true);// 扩大比例的缩放
        webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);// 自适应屏幕
        webview.getSettings().setLoadWithOverviewMode(true);
        webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);//取消硬件加速
//		webview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webview.getSettings().setAllowFileAccess(true);
        webview.getSettings().setDomStorageEnabled(true);
        webview.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
    }

    //点击返回键，返回上一个页面，而不是退出程序
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
            webview.goBack();// 返回前一个页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void selectPersent(String[] mCloudVoicersValue, String[] mCloudVoicersEntries, int selectedNum) {
        new AlertDialog.Builder(this).setTitle("发音人选项")
                .setSingleChoiceItems(mCloudVoicersEntries, // 单选框有几项,各是什么名字
                        selectedNum, // 默认的选项
                        new DialogInterface.OnClickListener() { // 点击单选框后的处理
                            public void onClick(DialogInterface dialog,
                                                int which) { // 点击了哪一项
                                mPresenter.changePersent(which, mCloudVoicersValue[which]);
                                dialog.dismiss();
                            }
                        }).show();
    }

    @Override
    public void setPlayType(boolean isPlay) {
        play.setChecked(isPlay);
    }
}
